import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { _HttpClient } from '@delon/theme';
import { environment } from '../../../../environments/environment';

@Component({
    selector: 'app-stream',
    templateUrl: './stream.component.html'
})

export class StreamComponent implements OnInit {
    dataSet: any = [];
    allChecked = false;
    indeterminate = false;
    Loading = false;
    disabledButton = true;
    displayData = [];
    lockHeadScroll = { y: window.innerHeight - 350 + 'px' };

    constructor(
        private datePipe: DatePipe,
        private http: _HttpClient,
    ) { }

    ngOnInit() {
        this.getList();
    }

    getList() {
        this.stream().subscribe((res: any) => {
            const data = [];
            for (const item of res) {
                data.push({
                    'id': item.id,
                    'pid':item.pid,
                    'page': item.page,
                    'stime': this.datePipe.transform(item.stime, 'yyyy-MM-dd'),
                    'etime':this.datePipe.transform(item.etime, 'yyyy-MM-dd'),
                    'os': item.os,
                    'browser': item.browser,
                    'ip': item.ip
                });
            }
            this.dataSet = data.reverse();
        });
    }

    // 操作记录
    stream() {
        return this.http.get(environment.apiBase + '/csmis/sysTactionlogs/query.jwt');
    }

    checkAll(value: boolean): void {
        this.displayData.forEach(data => {
            if (!data.disabled) {
                data.checked = value;
            }
        });
        this.refreshStatus();
    }

    refreshStatus(): void {
        const allChecked = this.displayData.filter(value => !value.disabled).every(value => value.checked == true);
        const allUnChecked = this.displayData.filter(value => !value.disabled).every(value => !value.checked);
        this.allChecked = allChecked;
        this.disabledButton = !this.dataSet.some(value => value.checked);
        this.indeterminate = (!allChecked) && (!allUnChecked);
    }

    currentPageDataChange($event: Array<{ id: string; page: number; time: string; os: string; browser: string; ip: string; }>): void {
        this.displayData = $event;
        this.refreshStatus();
    }

    delData() {
        this.Loading = true;
        this.displayData.forEach(data => {
            if (data.checked) {
                setTimeout(() => {
                    this.streamDel(data.id, () => {
                        this.dataSet = this.dataSet.filter(d => d.id != data.id);
                        this.Loading = false;
                    });
                }, 1000);
            }
        });
    }

    streamDel(id, callback) {
        if (callback) {
            this.http.get(environment.apiBase + '/csmis/sysTactionlogs/del.jwt?id=' + id).subscribe(res => {
                callback();
            });
        }
    }
}
